/*
 * @Author: fanjs
 * @Date: 2024-03-28 16:02:00
 * @Description: 计息日志模型
 */
import { Table, Column, DataType, ForeignKey, BelongsTo } from 'sequelize-typescript'
import { BaseModel } from '@core/db'
import BillModel from './bill'
import { DateUtil } from '@core/util'

export interface InterestLogAttributes {
  id?: number
  billId: number
  billName: string
  beforePrincipal: number
  beforeInterest: number
  currentInterest: number
  afterInterest: number
  count?: number
  operator: string
  operatorName: string
  status: 'success' | 'fail'
  error?: string
  created_at?: string
}

@Table({ tableName: 'interest_log' })
class InterestLogModel extends BaseModel<InterestLogModel, InterestLogAttributes> {
  @Column({
    type: DataType.INTEGER,
    primaryKey: true,
    autoIncrement: true,
  })
  declare id: number

  @ForeignKey(() => BillModel)
  @Column
  declare billId: number

  @BelongsTo(() => BillModel)
  bill!: BillModel

  @Column({
    type: DataType.STRING,
    comment: '账单名称',
  })
  declare billName: string

  @Column({
    type: DataType.DECIMAL(10, 2),
    comment: '计息前本金',
  })
  declare beforePrincipal: number

  @Column({
    type: DataType.DECIMAL(10, 2),
    comment: '计息前利息',
  })
  declare beforeInterest: number

  @Column({
    type: DataType.DECIMAL(10, 2),
    comment: '本次计息金额',
  })
  declare currentInterest: number

  @Column({
    type: DataType.DECIMAL(10, 2),
    comment: '计息后利息',
  })
  declare afterInterest: number

  @Column({
    type: DataType.INTEGER,
    comment: '计息次数',
    defaultValue: 0,
  })
  declare count: number

  @Column({
    type: DataType.STRING,
    comment: '操作人ID',
  })
  declare operator: string

  @Column({
    type: DataType.STRING,
    comment: '操作人昵称',
  })
  declare operatorName: string

  @Column({
    type: DataType.ENUM('success', 'fail'),
    comment: '计息状态',
  })
  declare status: 'success' | 'fail'

  @Column({
    type: DataType.STRING,
    comment: '错误信息',
  })
  declare error: string

  keys() {
    this.append('created_at')
  }

  /**
   * 创建计息日志
   * @param data 日志数据
   * @param options 创建选项
   * @returns 创建的日志记录
   */
  static async createLog(data: InterestLogAttributes, options?: any) {
    return await InterestLogModel.create(data, options)
  }

  /**
   * 获取计息日志列表
   * @param billId 账单ID
   * @param page 页码
   * @param pageSize 每页数量
   * @returns 日志列表和分页信息
   */
  static async getLogList(billId: number, page: number = 1, pageSize: number = 10) {
    const { count, rows } = await InterestLogModel.findAndCountAll({
      where: { billId },
      order: [['created_at', 'DESC']],
      offset: (page - 1) * pageSize,
      limit: pageSize
    })

    const formattedRows = rows.map(item => {
      const logData = item.toJSON()
      return {
        ...logData,
        created_at: DateUtil.formatDateTime(logData.created_at)
      }
    })

    return {
      total: count,
      list: formattedRows,
      page,
      pageSize
    }
  }
}

export default InterestLogModel 